package com.dorm.cj.threadlocal;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test_threadLocal {

    private static ExecutorService pool = Executors.newFixedThreadPool(6);

    private static int count = 10;

    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 10;
        }
    };

    /**
     * threadLocal:每个线程独立，数据更新不影响其他线程
     */

    public static void main(String[] args) {
        try {
            CountDownLatch latch = new CountDownLatch(10);
            for (int i = 0; i < 10; i++) {
                pool.execute(() -> {
                    //                如果在此处latch.countDown()，则必须pool的size>=10.否则阻塞无法执行
                    //                latch.countDown();
                    //                System.out.println(latch.getCount());
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //                count = count - 1;
                    //                System.out.println(Thread.currentThread().getName() + "count:" + count);
                    threadLocal.set(threadLocal.get() - 1);
                    System.out.println(Thread.currentThread().getName() + "threadLocal:" + threadLocal.get());
                });
                latch.countDown();
            }
        } finally {
            // 防止内存溢出，显示调用threadLocal.remove()
            threadLocal.remove();
        }
    }
}
